package org.jeecg.modules.qy_wechat.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.qy_wechat.entity.QyWechat;
import org.jeecg.modules.qy_wechat.service.IQyWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Api(tags = "企业微信")
@RestController
@RequestMapping("/qy_wechat/qyWechat")
public class QyWechatController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${qywechat.nurse.corpId:}")
    private String corpId;

    @Value("${qywechat.nurse.secret:}")
    private String secret;

    @Autowired
    private IQyWechatService qyWechatService;


    @GetMapping("getKfUrl")
    @AutoLog(value = "企业微信-获取客服Url")
    @ApiOperation(value = "企业微信-获取客服Url", notes = "企业微信-获取客服Url")
    @ResponseBody
    public Result<?> getKfUrl(
            @RequestParam(name = "openKfid", required = true) String openKfid

    ) {

        JSONObject jsonObject = null;

        Map<String, String> params = new HashMap<>();

        String result;

        String access_token;

        String url;

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
        if (oConvertUtils.isNotEmpty(openKfid)) {
            if (redisUtil.hasKey("qywx_access_token")&& oConvertUtils.isNotEmpty(redisUtil.get("qywx_access_token"))) {
                access_token = redisUtil.get("qywx_access_token").toString();
            } else {
                url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpId+"&corpsecret="+secret;

                params.put("corpid", corpId);

                params.put("corpsecret", secret);

                result = restTemplate.getForEntity(url, String.class, params).getBody();

                jsonObject = JSON.parseObject(result);

                access_token = jsonObject.getString("access_token");

                redisUtil.set("qywx_access_token", access_token, 7000);
            }
            params.clear();
            url = "https://qyapi.weixin.qq.com/cgi-bin/kf/add_contact_way?access_token=" + access_token;

            params.put("access_token", access_token);
            params.put("open_kfid", openKfid);
            params.put("scene", "12345");

            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/kf/add_contact_way?access_token=" + access_token);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000)
                    .build();
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(params), ContentType.create("application/json", "utf-8")));
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            org.apache.http.HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
            jsonObject = JSONObject.parseObject(result);
            Integer errcode = jsonObject.getInteger("errcode");
            if (0 == errcode) {
                return Result.OK(jsonObject);
            }
        }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error(jsonObject.getString("errmsg"));
    }

    @GetMapping("over")
    @ResponseBody
    public Result<?>  test(HttpServletRequest request
    ) {
        System.out.println("回调成功！！");
        return Result.ok();
    }




    /**
     * 创建企业微信应用聊天群
     */
    @PostMapping("/create")
    @ApiOperation(value = "创建应用聊天群", notes = "调用企业微信接口创建内部聊天群 name 群名称 owner 群主userid userlist List<String>成员表")
     public Result<?> createAppChat(@Valid @RequestBody QyWechat appChat,HttpServletRequest req) {
        try {
//            QyWechat wechatChat = new QyWechat();
//            wechatChat.setName("项目研发群");
//            wechatChat.setOwner("LiHang");
//            wechatChat.setUserlist(Arrays.asList("LiHang", "JiangSiZhi", "LiPingAn"));
            appChat.setStatus(0); // 0=正常

            // 调用服务层创建聊天群
            String result = qyWechatService.createAppChat(appChat,req.getHeader("sys_org_code"));
            return Result.OK("创建成功", result);
        } catch (Exception e) {
            log.error("创建企业微信聊天群失败", e);
            return Result.error("创建失败：" + e.getMessage());
        }
    }



}
